import {defineAsyncComponent} from 'vue';
import {guid} from '@/utils/CommonUtils';

export default {
  name: 'DefaultDynamicComponent',
  data() {
    return {
      componentPath: 'views/Empty',
      key: guid(),
      componentLoaded: () => {
      }
    };
  },
  methods: {
    setComponent(componentPath, callback) {
      this.componentPath = componentPath;
      this.setCallback(callback);
      this.refresh();
      this.$nextTick(this.componentLoaded);
    },
    setCallback(callback) {
      if (callback) {
        this.componentLoaded = callback;
      } else {
        this.componentLoaded = () => {
        };
      }
    },
    refresh() {
      this.key = guid();
    },
    invoke(methodName, ...args) {
      this.invokeWithRetry(50, methodName, args);
    },
    invokeWithRetry(retry, methodName, args) {
      if (retry-- > 0 && this.$refs.component) {
        this.$refs.component[methodName](...args);
      } else {
        setTimeout(() => {
          this.invokeWithRetry(retry, methodName, args);
        }, 200);
      }
    },
  },
  render() {
    let component = defineAsyncComponent(() => import('@/' + this.componentPath));
    return <component key={this.key} ref="component"/>;
  },
};
